package pt.biblioescala

object ControlSQL {
  def using[Closeable <: {def close(): Unit}, B](closeable: Closeable)(getB: Closeable => B): B = 
    try {
      getB(closeable)
    } finally {
      closeable.close()
    }
  
  import scala.collection.mutable.ListBuffer
  
  def bmap[T](test: => Boolean)(block: => T): List[T] = {
    val ret = new ListBuffer[T]
    while(test) ret += block
    ret.toList
  }
  
  import java.sql._
  
  /** Executes the SQL and processes the result set using the specified function. */
  def query[B](connection: Connection, sql: String)(process: ResultSet => B): B =
	  using (connection.createStatement) { statement => 
	    using (statement.executeQuery(sql)) { results => 
	      process(results)
	    }
  }
  
  /** Updates the SQL DB and processes the result set using the specified function. */
  def update[B](connection: Connection, sql: String) =
	  using (connection.createStatement) { statement => 
    statement.executeUpdate(sql)
  }

  /** Executes the SQL and uses the process function to convert each row into a T. */
  def queryEach[T](connection: Connection, sql: String)(process: ResultSet => T): List[T] =
    query(connection, sql) { results => 
      bmap(results.next) { 
        process(results)
      }
    }
}